//
//  LXNetMgr.m
//  ZuLinProject
//
//  Created by 谭明星 on 2021/12/6.
//

#import "LXNetMgr.h"
#import "JSONMgr.h"
#import "AppDelegate+Net.h"
//#import <UMCommon/MobClick.h>
//代理
#import <CFNetwork/CFNetwork.h>
#import <arpa/inet.h>
#import <netinet/in.h>
#import <ifaddrs.h>
//解密
#import "JSONMgr.h"
#import "SSKeyChainMgr.h"
#import "NSData+XPAES128.h"
#import "OYCountDownManager.h"
#import "YLReqest.h"
#import "LoginPageViewController.h"
//token过期, 重登录
//#import "BaseNavController.h"
//#import "YLLoginViewController2.h"
static NSString * kKCSer = @"9F2BA010252C41CA";

#pragma mark -------------------发起请求------------------
@implementation LXNetMgr

/** 请求参数未加密, 使用此方法 */
+ (void)reqNoEncrypt:(YTKBaseRequest *)req
             success:(void(^)(YTKBaseRequest *req, NSDictionary *resDic))success
             failure:(void(^)(YTKBaseRequest *req))failure {
    if ([self detectiveHttpDelegate]) { //使用了代理
        dispatch_async(dispatch_get_main_queue(), ^{
            if (failure){
                failure([LXGetRequest new]);
            }
        });
        return;
    }
//    if ([AFNetworkReachabilityManager sharedManager].isReachable){
        [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary * dic = [JSONMgr getJsonDic:request.responseData];
            //NSLog(@"<-- %s, %d --> 🐔服务器数据🐔%@", __FUNCTION__, __LINE__, dic);
            id result = dic[@"code"];
                if ([dic[@"code"] intValue] == RESPONSE_CODE_TOKEN_INVALID) {//token过期
                    NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, dic);
                    [self showLoginAlert];
                } else {
                    if (success){
                        success(request, dic);
                    }
                }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, request.error.localizedDescription);
            if (failure) {
                failure(request);
            }
        }];
    }
//else {
//         // [self showNoNetAlert];
//    }
    


@end


#pragma mark - ------------------ 解密 ------------------
@implementation LXNetMgr (Decrypt)
+ (NSData *)decryptResponseObj:(NSData *)responseObj {
    NSError * error;
    NSString * jsonObj = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:&error];
    //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, jsonObj);
//    if (error) {
//        NSLog(@"<-- %s, %d --> 解析出错了: %@", __FUNCTION__, __LINE__, error.localizedDescription);
//        return nil;
//    } else {
        NSDictionary * jsonDic = [JSONMgr dicFromJsonString:jsonObj];
        //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, jsonDic);
        NSString * jsonCt = [NSString stringWithFormat:@"%@", jsonDic[@"ct"]];
        //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, jsonCt);
    
        //AES 解密
        NSData * decodeData = [[NSData alloc] initWithBase64EncodedString:jsonCt options:NSDataBase64DecodingIgnoreUnknownCharacters];
        //NSString * aesKey = [SSKeyChainMgr getAESKey];
        NSData * resultData = [decodeData AES128DecryptWithKey:kKCSer iv:kKCSer];
        return resultData;
//    }
}
@end


#pragma mark - ------------------ 弹窗 ------------------
@implementation LXNetMgr (Alert)
+ (void)showNoNetAlert {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
            //NSLog(@"<<-- %@ -->>", keyWindow.subviews);
            for (UIView * subView in keyWindow.subviews) {
                if ([subView isKindOfClass:MBProgressHUD.class]) {
                    MBProgressHUD * hud = (MBProgressHUD *)subView;
                    [hud hideAnimated:NO];
                }
            }

            NSString * alertMsg = @"请手动前往手机设置内允许\"利行租赁端\"使用网络";
            if ([[UIApplication sharedApplication] canOpenURL:[UIApplicationOpenSettingsURLString toUrl]]) {
                alertMsg = @"请检查您手机的网络设置, 并允许\"利行租赁端\"使用网络";
            }
            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"网络开小差了" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                 [[UIApplication sharedApplication] openURL:[UIApplicationOpenSettingsURLString toUrl]];
            }]];
            UIViewController * rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
            //防止重复弹
            if ([rootVC.presentedViewController isKindOfClass:UIAlertController.class]) {
                return;
            }
            //弹窗消失后才能重弹
            if (rootVC.presentedViewController) {
                [rootVC.presentedViewController dismissViewControllerAnimated:NO completion:^{
                    [rootVC presentViewController:alertVC animated:YES completion:nil];
                }];
            } else {
                [rootVC presentViewController:alertVC animated:YES completion:nil];
            }
        });
    });
}

+ (void)showLoginAlert {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
            //NSLog(@"<<-- %@ -->>", keyWindow.subviews);
            for (UIView * subView in keyWindow.subviews) {
                if ([subView isKindOfClass:MBProgressHUD.class]) {
                    MBProgressHUD * hud = (MBProgressHUD *)subView;
                    [hud hideAnimated:NO];
                }
            }
            //防止重复弹
            UIViewController * rootVC = keyWindow.rootViewController;
            //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
            if ([rootVC.presentedViewController isKindOfClass:UIAlertController.class]) {
                return;
            }
            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"该账号已在其他设备登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                [[MSStorageUtils shareInstance] userDefaultSave:@"NO" withKey:USER_DEFAULT_KEY_MEMBER_IsLogin];
                [[SDWebImageDownloader  sharedDownloader] cancelAllDownloads];
                [[YTKNetworkAgent sharedAgent] cancelAllRequests];
                [[OYCountDownManager manager] invalidate];
                [SSKeyChainMgr delLoginToken];
                [YLUserMgr deleteUser];
                LoginPageViewController  *pageVC=[[LoginPageViewController  alloc] init];
                UINavigationController   *navigationVC=[[UINavigationController alloc] initWithRootViewController:pageVC];
                UIWindow  *  mainWindow =[BaseViewController getCurrentWindow];
                [mainWindow setRootViewController:navigationVC];
            }]];
            [rootVC presentViewController:alertVC animated:YES completion:nil];
        });
    });
}
+ (void)hideAlert {
    UIViewController * rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    //NSLog(@"<-- %s, %d --> %@", __FUNCTION__, __LINE__, rootVC);
    if (rootVC.presentedViewController) {
        [rootVC.presentedViewController dismissViewControllerAnimated:NO completion:nil];
    }
}

@end

#pragma mark - ------------------ 代理 ------------------
@implementation LXNetMgr (Delegate)
+ (BOOL)detectiveHttpDelegate {
    //获取wifi信息
//    NSDictionary * wifiDict = [self getLocalInfoForCurrentWiFi];
//    NSLog(@"-->>>>-wifiDict>>>>--%@", wifiDict);
//    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
    NSString * proxy = [self fetchHttpProxy];
//    CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - startTime);
//    NSLog(@"Linked in %f ms", linkTime * 1000.0);
    if (proxy) {
        //NSLog(@"----🔥使用了代理---%@", proxy);
        return YES;
    } else {
        //NSLog(@"----🔥没有使用代理---%@", proxy);
        return NO;
    }
}
+ (id)fetchHttpProxy {
    CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings();
    const CFStringRef proxyCFstr = CFDictionaryGetValue(dicRef, (const void*)kCFNetworkProxiesHTTPProxy);
    NSString *proxy = (__bridge NSString *)(proxyCFstr);
    return proxy;
}

+ (NSMutableDictionary *)getLocalInfoForCurrentWiFi {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        //*/
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    //----192.168.1.255 广播地址
                    NSString *broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
                    if (broadcast) {
                        [dict setObject:broadcast forKey:@"broadcast"];
                    }
                    NSLog(@"broadcast address--%@",broadcast);
                    //--192.168.1.106 本机地址
                    NSString *localIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    if (localIp) {
                        [dict setObject:localIp forKey:@"localIp"];
                    }
                    NSLog(@"local device ip--%@",localIp);
                    //--255.255.255.0 子网掩码地址
                    NSString *netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
                    if (netmask) {
                        [dict setObject:netmask forKey:@"netmask"];
                    }
                    NSLog(@"netmask--%@",netmask);
                    //--en0 端口地址
                    NSString *interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
                    if (interface) {
                        [dict setObject:interface forKey:@"interface"];
                    }
                    NSLog(@"interface--%@",interface);
                    return dict;
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    return dict;
}

+ (void)getWithUrl:(NSString *)requestUrl body:(NSMutableDictionary *)params success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failur
{
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //如果你不需要将通过body传 那就参数放入parameters里面
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:[NSString stringWithFormat:@"%@%@",DOMAIN_URL,requestUrl] parameters:nil error:nil];
    NSLog(@"%@%@",DOMAIN_URL,requestUrl);
    request.timeoutInterval= 10;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置body 在这里将参数放入到body
    [request setHTTPBody:nil];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",nil];
    manager.responseSerializer = responseSerializer;
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        if(responseObject != nil){
            NSDictionary * dic = [JSONMgr getJsonDic:responseObject];
            NSLog(@"-------%@",dic);
            success(dic);
        }
        if (error){
            failur(error);
        }
        
    }]resume];
}

+ (void)postWithUrl:(NSString *)requestUrl body:(NSMutableDictionary *)params success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failur
{
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //如果你不需要将通过body传 那就参数放入parameters里面
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",DOMAIN_URL,requestUrl] parameters:nil error:nil];
    
    request.timeoutInterval= 10;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置body 在这里将参数放入到body
    [request setHTTPBody:nil];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",nil];
    manager.responseSerializer = responseSerializer;
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
        if(responseObject != nil){
            NSDictionary * dic = [JSONMgr getJsonDic:responseObject];
            NSLog(@"-------%@",dic);
            success(dic);
        }
        if (error){
            failur(error);
        }
        
    }]resume];
}

@end

